package com.sauro.study.controller;

import com.alibaba.fastjson.JSON;
import com.sauro.common.model.dto.Result;
import com.sauro.study.model.UserInfo;
import com.sauro.study.service.UserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试
 *
 * @author lxk
 */
@Controller
@RequestMapping(value = "/test")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    /**
     * Get请求
     *
     * @return
     * @ResponseBody 注释后表示放回的是字符串
     */
    @GetMapping
    @ResponseBody
    public String queryAll() {
        List<UserInfo> userInfoList = userInfoService.queryAll();
        return JSON.toJSONString(userInfoList);
    }

    /**
     * 使用了RestFull风格
     *
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    @ResponseBody
    public String query(@PathVariable(value = "id") Integer id) {
        UserInfo userInfo = userInfoService.queryById(id);
        List<UserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(userInfo);
        return JSON.toJSONString(userInfoList);
    }

    /**
     * post请求
     *
     * @param userInfo
     * @return
     * @RequestBody 表示接收请求是JSON格式的数据
     */
    @PostMapping("/post/add")
    @ResponseBody
    public String add(@RequestBody UserInfo userInfo) {
        System.out.println("此请求没有经过拦截器");
        userInfoService.add(userInfo);
        return "添加OK";
    }

    /**
     * Delete请求
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        userInfoService.delete(id);
        return "删除成功";
    }

    /**
     * Put请求
     */
    @PutMapping("/update/{id}")
    @ResponseBody
    public Result update(@PathVariable("id") Integer id, @RequestBody UserInfo userInfo) {
        userInfo.setId(id);
        userInfoService.update(userInfo);
        return Result.success("修改成功");
    }

}
